import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { generateRandomStr } from 'src/untils/base62RandomStr';
import { Repository } from 'typeorm';
import { ShortUrl } from './entities/short-url.entity';
import { ShortLongMap } from './entities/short-long-map.entity';

@Injectable()
export class ShortUrlService {
    @InjectRepository(ShortUrl)
    private shortUrlRepository: Repository<ShortUrl>;

    @InjectRepository(ShortLongMap)
    private shortLongMapRepository: Repository<ShortLongMap>;

    // 批量生成code
    // 生成随机的长度为 6 的字符串，查下数据库，如果没查到，就插入数据，否则重新生成。
    async generateCode() {
        let str = generateRandomStr(6);
        const uniqueCode = await this.shortUrlRepository.findOneBy( {
            code: str
        });
        if(!uniqueCode) {
            const code = new ShortUrl();
            code.code = str;
            code.status = 0;
            return await this.shortUrlRepository.insert(code);
        } else {
            return this.generateCode();
        }
    }

    // longUrl生成短链方法
    /* 
    这里就是先从 short-url 表里取一个压缩码来用，如果没有可用压缩码，那就生成一个。
    然后在 short-long-map 表里插入这条新的短链映射，并且把用到的压缩码状态改为 1。
    */
    async generate (longUrl:string){
        let uniqueCode = await this.shortUrlRepository.findOneBy( {
           status : 0
        });

        if(!uniqueCode) {
            uniqueCode = await this.generateCode();
        }
        const map = new ShortLongMap();
        map.shortUrl = uniqueCode.code;
        map.longUrl = longUrl;
        console.log(map);
        
        // 存入短链map
        await this.shortLongMapRepository.insert(map); 
        // 更新short-url
        await this.shortUrlRepository.update({
            id: uniqueCode.id
        }, {
            status: 1
        });
        return uniqueCode.code;
    }


    // 查询code方法
    async getLongUrl(code:string){
        const map = await this.shortLongMapRepository.findOneBy({shortUrl:code})
        if(!map){
            return "未查询到"
        }
        return map.longUrl
    }
}
